const BaseService = require('./base_service.js');
const AppointmentModel = require('../model/appointment_model.js');
const UserModel = require('../model/user_model.js');

class OrderManagementService extends BaseService {

  /**
   * 获取订单列表
   */
  async getOrderList(input) {
    const db = uniCloud.database();
    const collection = db.collection(AppointmentModel.CL);

    // 构建查询条件
    let whereCondition = {};
    
    if (input.status !== undefined) {
      whereCondition.status = input.status;
    }
    
    if (input.storeId) {
      whereCondition.storeId = input.storeId;
    }
    
    if (input.userId) {
      whereCondition.userId = input.userId;
    }
    
    if (input.dateRange) {
      const dates = input.dateRange.split(',');
      if (dates.length === 2) {
        whereCondition.createTime = db.command.gte(parseInt(dates[0])).and(db.command.lte(parseInt(dates[1])));
      }
    }
    
    if (input.search) {
      whereCondition.orderId = new RegExp(input.search, 'i');
    }

    // 分页查询
    const result = await collection
      .where(whereCondition)
      .orderBy('createTime', 'desc')
      .skip((input.page - 1) * input.size)
      .limit(input.size)
      .get();

    // 获取总数
    const countResult = await collection.where(whereCondition).count();

    // 获取用户信息
    const userIds = [...new Set(result.data.map(item => item.userId))];
    const userCollection = db.collection(UserModel.CL);
    const users = await userCollection.where({
      _id: db.command.in(userIds)
    }).get();

    const userMap = {};
    users.data.forEach(user => {
      userMap[user._id] = user;
    });

    // 合并用户信息
    result.data.forEach(order => {
      order.userInfo = userMap[order.userId] || {};
    });

    return {
      list: result.data,
      total: countResult.total,
      page: input.page,
      size: input.size
    };
  }

  /**
   * 取消订单
   */
  async cancelOrder(input) {
    const db = uniCloud.database();
    const collection = db.collection(AppointmentModel.CL);

    // 检查订单是否存在
    const order = await collection.doc(input.orderId).get();
    if (!order.data.length) {
      throw new Error('订单不存在');
    }

    const orderData = order.data[0];

    // 检查订单状态
    if (orderData.status === 0) {
      throw new Error('订单已取消');
    }

    if (orderData.status === 2) {
      throw new Error('订单已完成，无法取消');
    }

    // 更新订单状态
    await collection.doc(input.orderId).update({
      status: 0,
      cancelReason: input.reason,
      cancelTime: Date.now(),
      updateTime: Date.now()
    });

    // 处理退款
    let refundResult = null;
    if (orderData.payStatus === 1) {
      refundResult = await this.processRefund(orderData, input.refundType);
    }

    return {
      message: '订单取消成功',
      refundResult: refundResult
    };
  }

  /**
   * 获取订单详情
   */
  async getOrderDetail(orderId) {
    const db = uniCloud.database();
    const collection = db.collection(AppointmentModel.CL);

    const order = await collection.doc(orderId).get();
    if (!order.data.length) {
      throw new Error('订单不存在');
    }

    const orderData = order.data[0];

    // 获取用户信息
    const userCollection = db.collection(UserModel.CL);
    const user = await userCollection.doc(orderData.userId).get();
    orderData.userInfo = user.data[0] || {};

    return orderData;
  }

  /**
   * 获取订单用户联系方式
   */
  async getOrderUserContact(orderId) {
    const db = uniCloud.database();
    const collection = db.collection(AppointmentModel.CL);

    const order = await collection.doc(orderId).get();
    if (!order.data.length) {
      throw new Error('订单不存在');
    }

    const orderData = order.data[0];

    // 获取用户信息
    const userCollection = db.collection(UserModel.CL);
    const user = await userCollection.doc(orderData.userId).get();
    
    if (!user.data.length) {
      throw new Error('用户不存在');
    }

    const userData = user.data[0];

    return {
      userId: userData._id,
      nickName: userData.nickName,
      phone: userData.phone,
      avatarUrl: userData.avatarUrl
    };
  }

  /**
   * 处理退款
   */
  async processRefund(orderData, refundType) {
    if (refundType === 'balance') {
      // 退款到余额
      const userCollection = db.collection(UserModel.CL);
      await userCollection.doc(orderData.userId).update({
        balance: db.command.inc(orderData.totalAmount),
        updateTime: Date.now()
      });

      return {
        type: 'balance',
        amount: orderData.totalAmount,
        message: '退款已到账余额'
      };
    } else if (refundType === 'wechat') {
      // 微信支付退款
      // 这里应该调用微信支付退款API
      // 由于需要具体的支付配置，这里先模拟
      return {
        type: 'wechat',
        amount: orderData.totalAmount,
        message: '微信退款处理中'
      };
    }

    throw new Error('不支持的退款方式');
  }
}

module.exports = OrderManagementService;
